import { reactive, toRefs, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router'
export default function () {
  const $route = useRoute()
  const $router = useRouter()

  const data = reactive({
    search_text: '',
    route_flat: []
  })

  onMounted(() => {
    var route_content = $router.options.routes.filter((item) => item.path === "/")[0].children;
    recursion(route_content);
  })

  function recursion(route_content) {
    route_content.forEach((v) => {
      if (v.children) {
        v.meta && v.meta.title && data.route_flat.push({ value: v.meta.title, path: v.redirect });
        recursion(v.children);
      } else {
        v.meta && v.meta.title && data.route_flat.push({ value: v.meta.title, path: v.path });
      }
    });
  }

  function querySearch(queryString, cb) {
    var route_flat = data.route_flat;
    var results = queryString ? route_flat.filter(createFilter(queryString)) : route_flat;
    results.length || (results = [{ value: "找不到相关页面" }]);
    // 调用 callback 返回建议列表的数据
    cb(results);
  }
  function createFilter(queryString) {
    return (restaurant) => {
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
      );
    };
  }
  function handleSelect(item) {
    item.path == $route.path || $router.push(item.path);
    data.search_text = ''
  }
  return reactive({
    ...toRefs(data),
    querySearch,
    handleSelect
  })
}